import { thin } from "../thin3.mjs";
import thin_render from "./thin_render.mjs";

export default function ({
	header,
	template,
	data,
	render,
	onclose,
	width,
	height
}) {
	let _this;
	let popcontainer;
	let popmask;

	function pop_render() {
		_this = this;

		popmask = document.createElement("popmask");
		popmask.thin_data = data;
		popmask.style.zIndex = 1000;

		if (onclose) popmask.onclose = onclose;

		let popdiaglog = document.createElement("popdialog");

		popcontainer = document.createElement("popbody"); //弹出框-内容

		if (typeof width === "number") width += "px";
		popdiaglog.style.width = width || "800px";
		if (typeof height === "number") height += "px";
		popdiaglog.style.height = height || "600px";
		//popcontainer.style.overflowY = "scroll";
		popmask.appendChild(popdiaglog);

		let popheader = document.createElement("popheader"); //弹出框-标题

		popheader.onmousedown = function (ev) {
			var pos_offset = {
				x: popdiaglog.offsetLeft - ev.clientX,
				y: popdiaglog.offsetTop - ev.clientY
			};
			document.addEventListener("mouseup", mouseup);
			document.addEventListener("mousemove", mousemove);

			function mousemove(ev) {
				popdiaglog.style.left = pos_offset.x + ev.clientX + "px";
				popdiaglog.style.top = pos_offset.y + ev.clientY + "px";
			}

			function mouseup(ev) {
				document.removeEventListener("mousemove", mousemove);
				document.removeEventListener("mouseup", mouseup);
			}
		};

		let closeicon = document.createElement("closeicon");
		closeicon.innerText = "✕";
		closeicon.onclick = function () {
			popclose(this);
		};

		popheader.appendChild(closeicon);

		popdiaglog.appendChild(popheader);

		popdiaglog.appendChild(popcontainer);
		document.body.appendChild(popmask);

		thin_render(popheader, header);

		if (render !== undefined) {
			console.log("pop render");
			render({ container: popcontainer, data });
		} else {
			// console.log("pop render");
			if (template) thin(popcontainer).render(template, data);
		}
		return this;
	}
	return pop_render.call({
		render: (template, data) => {
			thin(popcontainer).render(template, data);
			return _this;
		},
		onclose: (fn) => {
			popmask.onclose = fn;
			return _this;
		}
	});
}

export function popclose(context) {
	let container = context;
	while (
		container.parentNode !== undefined &&
		container.tagName !== "POPMASK"
	) {
		container = container.parentNode;
	}
	// console.log({ container });

	if (container) {
		if (container.onclose) container.onclose();
		container.parentNode.removeChild(container);
	}
}
